package one.stand.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import one.stand.entity.websocket.CommodityInfoEntity;
import one.stand.model.GoodSpecModel;
import one.stand.model.GoodsModel;
import one.stand.model.GoodstypeModel;
import one.stand.model.ResultModel;
import one.stand.request.GoodSpecRequest;
import one.stand.request.GoodsRequest;
import one.stand.request.GoodstypeRequest;
import one.stand.request.essay.GoodsQuery;
import one.stand.response.GoodsResponse;
import one.stand.response.GoodstypeResponse;
import one.stand.response.essay.CompanyGoodsTypeResponse;
import one.stand.service.BaseService;
import one.stand.service.GoodsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
@Service
@Transactional
public class GoodsServiceImpl extends BaseService implements GoodsService {


    @Override
    public ResultModel selectGoodsTypeInfo(GoodstypeRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        GoodstypeModel model = new GoodstypeModel();
        BeanUtils.copyProperties(request, model);
        model.setCompanyId(request.getCId().intValue());
        List<GoodstypeModel> list = goodstypeMapper.selectGoodsType(model);
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        List<GoodstypeResponse> responseList = new ArrayList<>();
        list.forEach(obj -> {
            {
                GoodstypeResponse response = new GoodstypeResponse();
                BeanUtils.copyProperties(obj, response);
                responseList.add(response);
            }
        });
        return ResultModel.success(responseList);
    }

    @Override
    public ResultModel<Map<String, Object>> selectGoodsTypeInfoPC(GoodstypeRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        GoodstypeModel model = new GoodstypeModel();
        BeanUtils.copyProperties(request, model);
        model.setCompanyId(request.getCId().intValue());
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<GoodstypeModel> list = goodstypeMapper.selectGoodsType(model);
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        PageInfo<GoodstypeModel> pageInfo = new PageInfo<>(list);
        Map<String, Object> map = new HashMap<>(2);
        map.put("pageInfo", pageInfo);
        return ResultModel.success(map);

    }

    @Override
    public ResultModel getGoodsTypeInfo(GoodstypeRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        GoodstypeModel model = new GoodstypeModel();
        BeanUtils.copyProperties(request, model);
        model.setCompanyId(request.getCId().intValue());
        List<GoodstypeModel> list = goodstypeMapper.getGoodsType(model);
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        List<GoodstypeResponse> responseList = new ArrayList<>();
        list.forEach(obj -> {
            {
                GoodstypeResponse response = new GoodstypeResponse();
                BeanUtils.copyProperties(obj, response);
                responseList.add(response);
            }
        });
        return ResultModel.success(responseList);
    }

    @Override
    public ResultModel addGoodsType(GoodstypeRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        log.info("添加商品类型参数：{}", JSON.toJSONString(request));
        if (request.getRoleId() <= 0) {
            return ResultModel.fail("你不是企业管理员，无法操作！");
        }
        GoodstypeModel model = new GoodstypeModel();
        BeanUtils.copyProperties(request, model);
        int r;
        if (request.getGoodstypeId() != null) {
            r = goodstypeMapper.updateByPrimaryKeySelective(model);
        } else {
            model.setCompanyId(request.getCId().intValue());
            model.setSort(goodstypeMapper.getGoodsTypeSortMax(model.getCompanyId()) + 1);
            model.setCreateTime(currentDate());
            model.setIsDel(0);
            r = goodstypeMapper.insertSelective(model);
        }
        if (r > 0) {
            return ResultModel.success(model.getGoodstypeId());
        }
        return ResultModel.fail();
    }

    @Override
    public ResultModel delGoodsType(GoodstypeRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        if (request.getRoleId() <= 0) {
            return ResultModel.fail("你不是企业管理员，无法操作！");
        }
        // 删除商品类型
        int r = goodstypeMapper.delGoodsType(request.getGoodstypeId());
        if (r > 0) {
            // 删除商品信息
            goodstypeMapper.delGoods(request.getGoodstypeId());
            // 删除商品规格
            goodstypeMapper.delGoodSpec(request.getGoodstypeId());
            // 删除商品类型
            goodstypeMapper.delGoodPhoto(request.getGoodstypeId());
            return ResultModel.success();
        }
        return ResultModel.fail("删除商品类型失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultModel moveGoodsType(GoodstypeRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        } else if (request.getGoodstypeId() == null) {
            return ResultModel.checkParamFail("goodstypeId为空");
        } else if (request.getType() == null) {
            return ResultModel.checkParamFail("type为空");
        }
        log.info("商品类型移动：{}", JSON.toJSONString(request));
        if (request.getRoleId() <= 0) {
            return ResultModel.fail("你不是企业管理员，无法操作！");
        }
        GoodstypeModel model = new GoodstypeModel();
        model.setGoodstypeId(request.getGoodstypeId());
        model.setType(request.getType());
        model.setCompanyId(request.getCId().intValue());
        // 查询被上移的商品分类id
        GoodstypeModel goodsTypeModel = goodstypeMapper.getThanGoodsTypeId(model);
        if (goodsTypeModel == null) {
            if (ONE.equals(request.getType())) {
                return ResultModel.fail("到顶了，无法上移！");
            } else if (TWO.equals(request.getType())) {
                return ResultModel.fail("到底了，无法下移！");
            }
        }
        // 修改分类
        model.setSort(goodsTypeModel.getSort());
        if (goodstypeMapper.moveGoodsType(model) > 0) {
            model = new GoodstypeModel();
            model.setGoodstypeId(goodsTypeModel.getGoodstypeId());
            model.setSort(goodsTypeModel.getLastSort());
            goodstypeMapper.moveGoodsType(model);
            return ResultModel.success();
        }
        return ResultModel.fail("修改分类失败");
    }

    @Override
    public ResultModel getGoodsInfo(GoodsRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        GoodsModel model = new GoodsModel();
        model.setGoodsId(request.getGoodsId());
        model.setIsDel(0);
        List<GoodsModel> list = goodsMapper.getGoodsInfo(model);
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        List<GoodsResponse> responseList = new ArrayList<>();
        list.forEach(obj -> {
            {
                GoodsResponse response = new GoodsResponse();
                BeanUtils.copyProperties(obj, response);
                responseList.add(response);
            }
        });
        return ResultModel.success(responseList);
    }

    @Override
    public ResultModel<Map<String, Object>> getGoodsInfoPC(GoodsRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        GoodsModel model = new GoodsModel();
        BeanUtils.copyProperties(request, model);
        model.setCompanyId(request.getCId().intValue());
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        model.setIsDel(0);
        List<GoodsModel> list = goodsMapper.getGoodsInfo(model);
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        PageInfo<GoodsModel> pageInfo = new PageInfo<>(list);
        Map<String, Object> map = new HashMap<>(2);
        map.put("pageInfo", JSON.toJSONString(pageInfo));
        return ResultModel.success(map);
    }

    @Override
    public ResultModel<Boolean> moveGoodsInfo(GoodsRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        } else if (request.getGoodsId() == null) {
            return ResultModel.checkParamFail("goodsId为空");
        } else if (request.getType() == null) {
            return ResultModel.checkParamFail("type为空");
        }
        log.info("商品信息移动：{}", JSON.toJSONString(request));
        GoodsModel model = new GoodsModel();
        model.setGoodsId(request.getGoodsId());
        model.setType(request.getType());
        model.setCompanyId(request.getCId().intValue());
        // 查询被移动的商品信息
        GoodsModel goodsModel = goodsMapper.getThanGoodsInfo(model);
        if (goodsModel == null) {
            if (ONE.equals(request.getType())) {
                return ResultModel.fail("到顶了，无法上移！");
            } else if (TWO.equals(request.getType())) {
                return ResultModel.fail("到底了，无法下移！");
            }
        }
        // 修改商品排序
        model.setSort(goodsModel.getSort());
        if (goodsMapper.moveGoodsInfo(model) > 0) {
            model = new GoodsModel();
            model.setGoodsId(goodsModel.getGoodsId());
            model.setSort(goodsModel.getLastSort());
            goodsMapper.moveGoodsInfo(model);
            return ResultModel.success(true);
        }
        return ResultModel.fail("修改商品排序失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultModel addGoodsInfo(GoodsRequest request) {
        log.info("添加商品：{}", JSON.toJSONString(request));
        if (request == null) {
            return ResultModel.checkParamFail();
        } else if (request.getGoodstypeId() == null) {
            return ResultModel.checkParamFail("goodstypeId为空");
        }
        if (request.getRoleId() <= 0) {
            return ResultModel.fail("你不是企业管理员，无法操作~！");
        }
        if (StringUtils.isBlank(request.getGoodsName())) {
            return ResultModel.fail("商品名称不能为空~！");
        }
        if (StringUtils.isBlank(request.getSpecIds())) {
            return ResultModel.fail("操作失败，请确认商品规格~！");
        }
        if (request.getSpecIds() != null && request.getSpecIds().length() >= 5000) {
            return ResultModel.fail("操作失败，商品规格数据过大，请简略~！");
        }
        GoodsModel model = new GoodsModel();
        BeanUtils.copyProperties(request, model);
        int r;
        if (request.getGoodsId() != null && request.getGoodsId() > 0) {
            r = goodsMapper.updateByPrimaryKeySelective(model);
        } else {
            model.setCompanyId(request.getCId().intValue());
            model.setCreateTime(currentDate());
            model.setIsDel(0);
            model.setSort(goodsMapper.getGoodsInfoSortMax(new GoodsModel() {{
                setCompanyId(request.getCId().intValue());
            }}));
            r = goodsMapper.insertSelective(model);
        }
        if (r > 0) {
            // 删除以前的商品规格
            goodSpecMapper.delGoodSpec(model.getGoodsId());
            // 重新绑定商品规格
            GoodSpecModel goodSpecModel = new GoodSpecModel();
            goodSpecModel.setGoodsId(model.getGoodsId());
            goodSpecModel.setSpecIds(request.getSpecIds().split(ARRAY_SYMBOL));
            goodSpecModel.setIsDel(0);
            goodSpecMapper.updateGoodsId(goodSpecModel);
            // 删除以前商品图片
            goodsMapper.delGoodPhoto(model.getGoodsId());
            // 重新添加商品图片
            if (model.getGoodPhoto() != null) {
                int n = 0;
                for (String photo : model.getGoodPhoto().split(ARRAY_SYMBOL)) {
                    GoodsModel goodsModel = new GoodsModel();
                    goodsModel.setGoodsId(model.getGoodsId());
                    goodsModel.setUrl(photo);
                    goodsModel.setSort(n++);
                    goodsModel.setCreateTime(currentDate());
                    goodsModel.setIsDel(0);
                    goodsModel.setCoverImg(request.getCoverImg());
                    goodsMapper.insertGoodsPhoto(goodsModel);
                }
            }
            return ResultModel.success();
        }
        return ResultModel.fail("添加商品失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultModel addGoodsInfoList(GoodsRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        } else if (request.getGoodstypeId() == null) {
            return ResultModel.checkParamFail("goodstypeId为空");
        }
        log.info("添加商品：{}", JSON.toJSONString(request));
        if (request.getRoleId() <= 0) {
            return ResultModel.fail("你不是企业管理员，无法操作~！");
        }
        if (StringUtils.isBlank(request.getGoodsName())) {
            return ResultModel.fail("商品名称不能为空~！");
        }
        if (request.getGoodSpecRequestList() == null) {
            return ResultModel.fail("操作失败，请确认商品规格~！");
        }
        GoodsModel model = new GoodsModel();
        BeanUtils.copyProperties(request, model);
        int r;
        if (request.getGoodsId() != null && request.getGoodsId() > 0) {
            r = goodsMapper.updateByPrimaryKeySelective(model);
        } else {
            model.setCompanyId(request.getCId() == null ? request.getRoleId() : request.getCId().intValue());
            model.setCreateTime(currentDate());
            model.setIsDel(0);
            model.setSort(goodsMapper.getGoodsInfoSortMax(new GoodsModel() {{
                setCompanyId(request.getCId() == null ? request.getRoleId() : request.getCId().intValue());
            }}));
            r = goodsMapper.insertSelective(model);
        }
        if (r > 0) {
            // 删除以前的商品规格
            goodSpecMapper.delGoodSpec(model.getGoodsId());
            // 重新绑定商品规格
            addGoodSpecList(request.getGoodSpecRequestList(), model.getGoodsId());
            // 删除以前商品图片
            goodsMapper.delGoodPhoto(model.getGoodsId());
            // 重新添加商品图片
            if (model.getGoodPhoto() != null) {
                int n = 0;
                for (String photo : model.getGoodPhoto().split(ARRAY_SYMBOL)) {
                    GoodsModel goodsModel = new GoodsModel();
                    goodsModel.setGoodsId(model.getGoodsId());
                    goodsModel.setUrl(photo);
                    goodsModel.setSort(n++);
                    goodsModel.setCreateTime(currentDate());
                    goodsModel.setIsDel(0);
                    goodsModel.setCoverImg(request.getCoverImg());
                    goodsMapper.insertGoodsPhoto(goodsModel);
                }
            }
            return ResultModel.success();
        }
        return ResultModel.fail("删除商品失败");
    }

    /**
     * 批量添加商品规格
     *
     * @param list
     * @param goodsId
     * @return
     */
    public ResultModel addGoodSpecList(List<GoodSpecRequest> list, Integer goodsId) {
        if (list == null || list.size() <= 0) {
            return ResultModel.checkParamFail("商品规格列表规格为空");
        }
        for (GoodSpecRequest request : list) {
            GoodSpecModel model = new GoodSpecModel();
            model.setGoodsId(goodsId);
            model.setSpecName(request.getSpecName());
            model.setIsDel(0);
            int r;
            if (request.getSpecId() == null) {
                model.setCreateTime(currentDate());
                r = goodSpecMapper.insertSelective(model);
            } else {
                model.setSpecId(request.getSpecId());
                r = goodSpecMapper.updateByPrimaryKeySelective(model);
            }
            if (r > 0) {
                if(request.getList() != null){
                    for (GoodSpecRequest request1 : request.getList()) {
                        GoodSpecModel model1 = new GoodSpecModel();
                        model1.setGoodsId(goodsId);
                        model1.setSpecNum(request1.getSpecNum());
                        model1.setPrice(request1.getPrice());
                        model1.setSpecAttribute(request1.getSpecAttribute());
                        model1.setParentId(model.getSpecId());
                        model1.setIsDel(0);
                        if (request1.getSpecId() == null) {
                            model1.setCreateTime(currentDate());
                            goodSpecMapper.insertSelective(model1);
                        } else {
                            model1.setSpecId(request1.getSpecId());
                            goodSpecMapper.updateByPrimaryKeySelective(model1);
                        }
                    }
                }
            }
        }
        return ResultModel.success();
    }

    @Override
    public ResultModel addGoodSpecInfo(GoodSpecRequest request) {
        log.info("添加商品规格：{}", JSON.toJSONString(request));
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        if (request.getRoleId() <= 0) {
            return ResultModel.fail("你不是企业管理员，无法操作！");
        }
        GoodSpecModel model = new GoodSpecModel();
        BeanUtils.copyProperties(request, model);
        int r;
        if (request.getSpecId() == null || request.getSpecId() <= 0) {
            model.setCreateTime(currentDate());
            model.setIsDel(0);
            r = goodSpecMapper.insertSelective(model);
            if (r > 0) {
                return ResultModel.success(model.getSpecId());
            }
        } else {
            r = goodSpecMapper.updateByPrimaryKeySelective(model);
        }
        if (r > 0) {
            return ResultModel.success(model.getSpecId());
        }
        return ResultModel.fail("添加商品规格失败");
    }

    @Override
    public ResultModel transferGoods(GoodsRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        if (request.getRoleId() <= 0) {
            return ResultModel.fail("你不是企业管理员，无法操作！");
        }
        GoodsModel model = new GoodsModel();
        model.setGoodsId(request.getGoodsId());
        model.setGoodstypeId(request.getGoodstypeId());
        int r = goodsMapper.updateByPrimaryKeySelective(model);
        if (r > 0) {
            return ResultModel.success();
        }
        return ResultModel.fail();
    }

    @Override
    public ResultModel delGoodsInfo(GoodsRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        if (request.getRoleId() <= 0) {
            return ResultModel.fail("你不是企业管理员，无法操作！");
        }
        GoodsModel model = new GoodsModel();
        model.setGoodsId(request.getGoodsId());
        if (request.getIsDel() == null) {
            model.setIsDel(1);
        } else {
            model.setIsDel(request.getIsDel());
        }
        if (goodsMapper.updateByPrimaryKeySelective(model) > 0) {
            /**goodSpecMapper.delGoodSpec(request.getGoodsId());*/
            return ResultModel.success();
        }
        return ResultModel.fail();
    }

    @Override
    public ResultModel delGoodSpecInfo(GoodSpecRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        if (request.getRoleId() <= 0) {
            return ResultModel.fail("你不是企业管理员，无法操作！");
        }
        GoodSpecModel model = new GoodSpecModel();
        BeanUtils.copyProperties(request, model);
        model.setIsDel(1);
        int r = goodSpecMapper.updateByPrimaryKeySelective(model);
        if (r > 0) {
            return ResultModel.success();
        }
        return ResultModel.fail();
    }

    @Override
    public ResultModel<CommodityInfoEntity> getSendMessage(Long specId) {
        return ResultModel.success(goodSpecMapper.getSendMessage(specId));
    }

    @Override
    public ResultModel<PageInfo<CompanyGoodsTypeResponse>> queryCompanyGoods(GoodsQuery request) {
        List<CompanyGoodsTypeResponse> companyGoodsTypeResponses = this.goodstypeMapper.queryCompanyGoodsType(request);
        if(companyGoodsTypeResponses == null){
            return ResultModel.noData();
        }
        companyGoodsTypeResponses.forEach(goodsTypeResponse -> {
            //查询商品
            goodsTypeResponse.setCompanyGoodsResponses(this.goodsMapper.getCompanyGoodsInfo(goodsTypeResponse.getGoodsTypeId()));
        });
        return ResultModel.success(companyGoodsTypeResponses);
    }
}
